﻿using System;
using System.Collections.Generic;

namespace xshare
{


    public class SysEvent
    {

        static Dictionary<string, List<Delegate>> s_listenerDict;
        static Dictionary<string, List<Delegate>> GetListenerDict()
        {
            if (null == s_listenerDict)
                s_listenerDict = new Dictionary<string, List<Delegate>>();

            return s_listenerDict;
        }

        public static void On(string eventName, Action<object> listener)
        {
            var dict = GetListenerDict();
            if (dict.TryGetValue(eventName, out var list))
            {
                if (!list.Contains(listener))
                    list.Add(listener);
            }
            else
            {
                list = new List<Delegate>();
                dict.Add(eventName, list);
                list.Add(listener);
            }
            
        }

        public static void Off(string eventName, Action<object> listener)
        {
            if (null == s_listenerDict)
                return;

            if (s_listenerDict.TryGetValue(eventName, out var list))
            {
                var index = list.IndexOf(listener);
                if (index >= 0)
                {
                    list[index] = null;
                }

                list.ClearNull();
            }
        }

        public static void Broadcast(string eventName, object data = null)
        {
            if (s_listenerDict.TryGetValue(eventName, out var list))
            {
                for (var i = 0; i < list.Count; ++i)
                {
                    var l = list[i];
                    if (null == l)
                        continue;

                    DelegateUtils.SafeInvokeDelegate(l, data);
                }
            }
        }


    } //end of class


}
